package LintCode;

/**
 * @Classname LongestSemiAlternatingSubstring
 * @Description TODO
 * @Date 2021/3/3 17:17
 * @Created by ASUS
 */
public class LongestSemiAlternatingSubstring {
    /**
     * @param s: the string
     *           Input: "baaabbabbb"
     * @return: length of longest semi alternating substring
     */
    public int longestSemiAlternatingSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        // s.length() must >= 1
        int preCount = 1;
        char preChar = s.charAt(0);
        int startIndex = 0, max = 0, i;
        for (i = 1; i < s.length(); i++) {
            if (s.charAt(i) == preChar) {// the next character is as same as the character before it.
                if (preCount == 2) {// the same character has already appeared for 2 times.
                    int length = i - startIndex ;
                    max = Math.max(length, max);
                    startIndex = i - 1;
                    preCount = 1;
                    preChar = s.charAt(i - 1);
                    i--;
                } else preCount++;
            } else {// the next character is not as same as the character before it.
                preChar = s.charAt(i);
                preCount = 1;
            }
        }
        return Math.max(max, i - startIndex);
    }

    public static void main(String[] args) {
        System.out.println(new LongestSemiAlternatingSubstring().longestSemiAlternatingSubstring("baaabbabbb"));
    }
}
